package com.beyond.parse.util;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class XmlUtil {

    public static String parseXml(String xmlPath) {
        Document doc;
        FileOutputStream out = null;
        XMLWriter writer = null;

        String targetPath = xmlPath.replace(".xml", "-temp.xml");
        try {
            doc = new SAXReader().read(new File(xmlPath));
            String content = doc.asXML();
            content = content.replaceAll("#\\{", "\\$\\{");
            doc = DocumentHelper.parseText(content);

            List<Element> elementList = doc.getRootElement().elements();
            if (elementList != null && elementList.size() > 0) {
                for (Element e : elementList) {
                    if ("resultMap".equals(e.getName())) {
                        e.detach();
                    } else if ("select".equals(e.getName()) || "update".equals(e.getName())
                        || "delete".equals(e.getName()) || "insert".equals(e.getName())) {
                        // 删除ResultMap、ResultType
                        Attribute resultMap = e.attribute("resultMap");
                        if (resultMap != null) {
                            resultMap.detach();
                        }

                        Attribute resultType = e.attribute("resultType");
                        if (resultType != null) {
                            resultType.detach();
                        }

                        // 修改或者新增parameterType
                        e.addAttribute("parameterType", "map");
                    }
                }
            }

            // 指定文件输出的位置
            out =new FileOutputStream(targetPath);

            // 创建写出对象
            writer=new XMLWriter(out);

            // 写出Document对象
            writer.write(doc);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }
}
